<?php
/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:
 * @LastEditors: liuhongbin
 * @LastEditTime: xxx
 */

namespace addons\cloud_market\controller\api;

use addons\cloud_market\model\CloudMarketOrder;
use addons\cloud_market\model\CloudMarketAddon;
use addons\cloud_market\model\CloudMarketAddonSku;
use addons\cloud_market\model\CloudMarketSite;
use addons\cloud_market\model\CloudMarketSiteAddon;
use addons\cloud_market\utils\Wechat;
use think\facade\Db;

/**
 * 订单接口
 */
class Order extends CloudMarketApiController
{
    protected $notApiLogin = ['notify_wechat', 'test'];
    protected $notApiCheck = '*';
//    /**
//     * @var \EasyWeChat\Payment\Application
//     */
//    private $wechatApp;
    /**
     * @var CloudMarketOrder
     */
    protected $model;

    protected function initialize()
    {
        parent::initialize();
        $this->model = new CloudMarketOrder();
        $this->wechatApp = (new Wechat())->getApp();
    }


    /**
     * 【商城-个人中心-订单】获取用户订单列表
     * @throws \think\db\exception\DbException
     */
    public function getOrderList()
    {
        $page = input('page', '0');
        $size = input('size', '10');
        $where = [];
        $keyword = input('keyword', '');
        if($keyword){
            // 同时搜索站点名称和域名
            $where[] = ['out_trade_no|transaction_id', 'like', "%{$keyword}%"];
        }
        $data = $this->model
            ->where(['user_id' => $this->getUser()->id])
            ->where($where)
            ->order('id', 'desc')
            ->append(['addon','site'])
            ->paginate([
                'page'      => $page,
                'list_rows' => $size
            ], false)->each(function ($item, $key) {
                $item['price'] = sprintf('%01.2f', $item['total_fee'] / 100);
                unset($item['other']);
                return $item;
            });
        return $this->success('', $data);
    }

    /**
     * 【商城-应用购买】获取订单确认页面应用产品信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getBuyAddonGoodsMsg()
    {
        $msg = $this->request->post();
        $aid = $msg['aid'];
        $sid = $msg['site_id'];
        $sku_id = $msg['sku_id'];
        if (!$aid || !$sid) {
            return $this->error("页面参数错误");
        }
        $data['addon'] = CloudMarketAddon::where(['id' => $aid])->field(['id', 'title', 'icon_image', 'price', 'service_price', 'user_id'])->with(['developer'])->find()->append(['new_version'])->toArray();
//        $data['addon']['new_version'] = (new CloudMarketAddon())->getNewVersion($aid);

        $sku = CloudMarketAddonSku::where(['id' => $sku_id])->find();
        if (!$sku) {
            $sku = array(
                'id'      => 0,
                'count'   => 1,
                'service' => 12,
                'price'   => $data['addon']['price']
            );
        }
        $data['addon']['sku'] = $sku;
        $data['site'] = CloudMarketSite::where(['id' => $sid])->field(['id', 'title', 'domain', 'version', 'user_id'])->find()->toArray();
        return $this->success($msg, $data);
    }

    public function getBuyAddonServerMsg()
    {
        // 站点应用id
        $siteAddonId = input('site_addon_id', 0);
        $siteAddon = (new CloudMarketSiteAddon())->where(['id' => $siteAddonId])->with(['addon', 'site'])->find();
        if (!$siteAddon) {
            return $this->error('当前数据不存在');
        }
        return $this->success('ok', $siteAddon);
    }

    /**
     * 【商城-购买应用】提交订单
     */
    public function submitOrder()
    {
        $post = $this->request->post('data/a', []);
        $user = $this->getUser();

        $aid = intval($post['aid']);
        $site_id = intval($post['sid']);
        $sku_id = intval($post['sku_id']);
        $order = $this->model->where(['aid' => $aid, 'user_id' => $user->id, 'site_id' => $site_id, 'sku_id' => $sku_id, 'type' => 'buy_addon'])->find();
        if ($order && (time() - strtotime($order['create_time'])) < 12 * 60 * 60) {
            return $this->success("已经存在订单", ['oid' => $order['id']]);
        }

        $addonModel = new CloudMarketAddon();
        $addon = $addonModel->getAddonMsgForOrderBySku($aid, $sku_id);
        \think\facade\Log::write(['addon' => $addon]);
        //订单ID
        $order = array(
            'aid'          => $aid,
            'user_id'      => $user->id,
            'site_id'      => $site_id,
            'sku_id'       => $sku_id,
            'out_trade_no' => "DK" . sprintf("%05d", $user->id) . date("Ymdhis"),
            'attach'       => $addon['title'],
            'total_fee'    => intval($addon['price'] * 100),
            'status'       => 0,
            'type'         => 'buy_addon',
            'other'        => $post
        );
        // 启动事务
        Db::startTrans();
        try {
            $this->model->save($order);
            $oid = $this->model->getLastInsID();
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error('提交订单失败,原因:' . $e->getMessage());
        }
        return $this->success('提交成功', ['oid' => $oid]);
    }

    /**
     * 【商城-通用提交订单】提交订单
     */
    public function submitCommonOrder()
    {
        $post = $this->request->post('data/a', []);
        $user = $this->getUser();
        $aid = intval($post['aid']);
        $site_id = intval($post['site_id']);
        $type = $post['type'] ?? '';
        $attach = $post['attach'] ?? '';
        $order = $this->model->where(['aid' => $aid, 'user_id' => $user->id, 'site_id' => $site_id, 'type' => $type])->find();
        if ($order && (time() - strtotime($order['create_time'])) < 12 * 60 * 60) {
            return $this->success("已经存在订单", ['oid' => $order['id']]);
        }
        $addon = (new CloudMarketAddon())->where(['id' => $aid])->find();
        if (!$addon) {
            return $this->error('暂无当前应用数据');
        }
        if ($type == 'buy_service') {
            $total_fee = intval($addon['service_price'] * 100);
        } elseif ($type == 'buy_token') {
            $token_key = $post['token_key'] ?? 0;
            $token_prices = $post['token_prices'] ?? [];
            $token = $token_prices[$token_key] ?? [];
            $addon_token = $addon['token_prices'][$token_key] ?? [];
            if ($token['number'] != $addon_token['number'] || $token['price'] != $addon_token['price']) {
                return $this->error('数据有误');
            }
            $total_fee = intval($addon_token['price'] * 100);
        } else {
            return $this->error('未知类型');
        }
        //订单ID
        $order = array(
            'aid'          => $aid,
            'user_id'      => $user->id,
            'site_id'      => $site_id,
            'sku_id'       => 0,
            'out_trade_no' => "DK" . sprintf("%05d", $user->id) . date("Ymdhis"),
            'attach'       => $attach,
            'total_fee'    => $total_fee,
            'status'       => 0,
            'type'         => $type,
            'other'        => $post
        );
        // 启动事务
        Db::startTrans();
        try {
            $this->model->save($order);
            $oid = $this->model->getLastInsID();
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error('提交订单失败,原因:' . $e->getMessage());
        }
        return $this->success('提交成功', ['oid' => $oid]);
    }

    /**
     * 【商城】获取微信支付二维码
     */
    public function getWechatQrcode()
    {
        $oid = $this->request->post('oid', '0');
        $order = $this->model->where(['id' => $oid])->find();
        if ($order['status'] != 0) {
            return $this->error("当前订单已经支付");
        }
        if ($order['create_time'] < (time() - 12 * 60 * 60)) {
            return $this->error('当前订单未过期');
        }
        $addon = CloudMarketAddon::where(['id' => $order['aid']])->find();
        $site = CloudMarketSite::where(['id' => $order['site_id']])->find();
        $data = array(
            'addon_name'   => $addon->title,
            'new_version'  => $addon->new_version ?? '',
            'out_trade_no' => $order['out_trade_no'],
            'price'        => sprintf('%01.2f', $order['total_fee'] / 100),
            'domain'       => $site['domain']
        );

        if ($order['total_fee'] > 0) {
            //付费订单
            if ($order['code_url']) {
                $data['code_url'] = $order['code_url'];
                return $this->success('支付成功', $data);
            } else {
                // 微信支付功能暂未实现，需要配置微信支付
//                return $this->error('微信支付功能暂未实现');
                $result = $this->wechatApp->order->unify([
                    'trade_type'   => 'NATIVE',
                    'product_id'   => $order['id'], // $message['product_id'] 则为生成二维码时的产品 ID
                    'body'         => $order['attach'],
                    'out_trade_no' => $order['out_trade_no'],
                    'total_fee'    => $order['total_fee'],
                ]);
                if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                    $order->code_url = $result['code_url'];
                    $order->save();
                    $data['code_url'] = $result['code_url'];
                    return $this->success('', $data);
                } else {
                    return $this->error('订单生成失败', $result);
                }
            }
        } else {
            //免费订单
            $data['code_url'] = "free";
            $order->code_url = $data['code_url'];
            $order->status = 1;
            $this->model->dealWithOrder($order['out_trade_no']);
            $order->save();
            return $this->success('支付成功', $data);
        }
    }

    /**
     * 【商城】微信支付回调
     */
    public function notify_wechat()
    {
        // 微信支付功能暂未实现，需要配置微信支付
        return $this->error('微信支付功能暂未实现');
        /*
        $app = $this->wechatApp;
        $response = $app->handlePaidNotify(function ($message, $fail) {
            \think\facade\Log::debug(['notify' => $message]);
            $this->model->dealWithOrder($message['out_trade_no']);
            return true;
        });
        $response->send();
        */
    }

    /**
     * 【商城】获取支付状态
     */
    public function getOrderStatus()
    {
        $oid = $this->request->post('oid', '0');
        $status = $this->model->where(['id' => $oid])->value('status');
        return $this->success('', $status);
    }
}
